﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using SuperKnowledgeDatabase2000Client.KennismanagementReference;
using System.Globalization;
using System.Threading;
using System.Collections.ObjectModel;
using System.Data;
using System.Net;
using System.Diagnostics;
using System.ComponentModel;

namespace SuperKnowledgeDatabase2000Client
{
    /// <summary>
    /// UI logica for MainWindow.xaml
    /// </summary>
    /// <remarks></remarks>
    public partial class MainWindow : Window
    {
        CreateCategorie cat = null;
        RemoveDocument removeArticle = null;
        SaveNewDocument windowSaveNewArticle = null;
        SaveExitNewDocument windowSaveExitNewArticle = null;
        SaveExistingDocument windowSaveExistingArticle = null;
        SaveExitExistingDocument windowSaveExitExistingArticle = null;
        RegisterReferenceAddress windowRegisterReferenceAddress = null;
        ObservableCollection<ArticleInformation> _ArticleCollection = new ObservableCollection<ArticleInformation>();

        BindingListCollectionView blcv;
        GridViewColumnHeader _lastHeaderClicked = null;
        ListSortDirection _lastDirection = ListSortDirection.Ascending;

        const int SEARCH = 0;  // window type search and show categories
        const int INFORMATION = 1; // window type information article
        const int PROBLEM = 2; // window type problem solution article

        int menuItemClicked = 0;
        int shownArticle = -1;
        bool newData = false;   // defines if a new article has been created
        bool catChanged = false;    // defines if a category has been changed
        bool tagsChanged = false;   // defines if tag hasbeen been changed 
        bool titleChanged = false;  // defines if a title has changed
        bool artikelChanged = false; // defines if an article text has changed
        bool problemChanged = false;    // defines if a problem text has been changed
        bool solutionChanged = false;   // defines if a solution text has been changed
        bool displayOutdatedFiles = false; // defines if old file versions are visable or not (1= visible)
        bool searched = false;
        string type = "all";  // type can be "all", "information", or "problem" 

        /// <summary>
        /// start up the GUI and initialize components
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            SetInformationStatus(false);
            txt_author.IsTabStop = false;
            btn_search.IsTabStop = false;
            list_categories.IsTabStop = false;
        }


        /// <summary>
        ///  defines window and properties for a new information article
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewInformation(object sender, RoutedEventArgs e)
        {
            menuItemClicked = INFORMATION;
            if (GetVisibility() == INFORMATION)
            {
                if (HeaderChanged() || artikelChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += NewSaveWindowOnInformationClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveWindowOnInformationClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    SetInformationStatus(false);
                    Reset();
                    NewInformationArticle();
                }
            }
            else if (GetVisibility() == PROBLEM)
            {
                if (HeaderChanged() || problemChanged || solutionChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += NewSaveWindowOnProblemClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveWindowOnProblemClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    SetInformationStatus(false);
                    Reset();
                    ChangeVisibility(INFORMATION);
                    NewInformationArticle();
                }
            }
            else
            {
                ChangeVisibility(INFORMATION);
                NewInformationArticle();
            }
        }

        /// <summary>
        /// sets up the GUI for a new information article
        /// </summary>
        private void NewInformationArticle()
        {
            if (!cb_cat.IsEnabled)
            {
                ResetTextfields();
                cb_cat.IsEnabled = true;
            }
            lb_headline.Content = "Niew informatie artikel";
            txt_author.Text = Properties.Settings.Default.LastName + " " + Properties.Settings.Default.FirstName.Substring(0, 1) + ".";
            cb_cat.SelectedIndex = 0;
            txt_rating_article.Text = "0";
            SetInformationStatus(true);
            newData = true;
        }


        /// <summary>
        /// defines window and properties for a new problem-solution article
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewProblem(object sender, RoutedEventArgs e)
        {
            menuItemClicked = PROBLEM;
            if (GetVisibility() == INFORMATION)
            {
                if (HeaderChanged() || artikelChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += NewSaveWindowOnInformationClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveWindowOnInformationClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    SetInformationStatus(false);
                    Reset();
                    ChangeVisibility(PROBLEM);
                    NewProblemArticle();
                }
            }
            else if (GetVisibility() == PROBLEM)
            {
                if (HeaderChanged() || problemChanged || solutionChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += NewSaveWindowOnProblemClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveWindowOnProblemClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    SetInformationStatus(false);
                    Reset();
                    NewProblemArticle();
                }
            }
            else
            {
                ChangeVisibility(PROBLEM);
                NewProblemArticle();
            }
        }

        /// <summary>
        ///  sets up the GUI for a new problem article
        /// </summary>
        private void NewProblemArticle()
        {
            if (!cb_cat.IsEnabled)
            {
                ResetTextfields();
                cb_cat.IsEnabled = true;
            }
            lb_headline.Content = "Niew oplossing voor een probleem";
            txt_author.Text = Properties.Settings.Default.LastName + " " + Properties.Settings.Default.FirstName.Substring(0, 1) + ".";
            cb_cat.SelectedIndex = 0;
            txt_rating_problem.Text = "0";
            SetInformationStatus(true);
            newData = true;
        }


        /// <summary>
        ///  creates a new category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewCategory(object sender, RoutedEventArgs e)
        {
            if (cat == null)
            {
                cat = new CreateCategorie();
                cat.Closed += catWindowClosed;
                cat.ShowDialog();
            }
        }
        
        /// <summary>
        ///  makes old file versions visible or invisble
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowOutdatedFiles(object sender, RoutedEventArgs e)
        {
            var item = sender as MenuItem;
            if (item.IsChecked)
            {
                displayOutdatedFiles = true;
            }
            else
            {
                displayOutdatedFiles = false;
            }
            RefreshMain();
        }


        /// <summary>
        ///  opens a popup window about the creators of this app 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowInfo(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("KM-Webservice-Client", "Auteur: C. Hessel, J. Mausbach", MessageBoxButton.OK, MessageBoxImage.Information);
        }


        /// <summary>
        ///   changes and registers a new server adress 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChangeEndpointAdress(object sender, RoutedEventArgs e)
        {
            windowRegisterReferenceAddress = new RegisterReferenceAddress();
            windowRegisterReferenceAddress.Owner = this;
            windowRegisterReferenceAddress.Closed += registerReferenceAddressClosed;
            windowRegisterReferenceAddress.Show();
        }


        /// <summary>
        ///  toggles window state to normal or maximized
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChangeWindowSize(object sender, RoutedEventArgs e)
        {
            var item = sender as MenuItem;
            if (item.IsChecked)
            {
                WindowState = WindowState.Maximized;
            }
            else
            {
                WindowState = WindowState.Normal;
            }
            base.OnStateChanged(e);

        }

        /// <summary>
        ///  shows popup with a save dialog based on something is changed or not
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowSaveDialog(object sender, RoutedEventArgs e)
        {
            if (GetVisibility() == INFORMATION)
            {
                if (HeaderChanged() || artikelChanged)
                {
                    if (newData)
                    {
                        windowSaveNewArticle = new SaveNewDocument();
                        windowSaveNewArticle.Closed += NewSaveWindowClosed;
                        windowSaveNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExistingArticle = new SaveExistingDocument();
                        windowSaveExistingArticle.Closed += ExistingSaveWindowClosed;
                        windowSaveExistingArticle.Show();
                    }
                }
                else
                {
                    MessageBox.Show("Geen aanpassingen doorgevoert", "Data opslaan", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            else if (GetVisibility() == PROBLEM)
            {
                if (HeaderChanged() || problemChanged || solutionChanged)
                {
                    if (newData)
                    {
                        windowSaveNewArticle = new SaveNewDocument();
                        windowSaveNewArticle.Closed += NewSaveWindowClosed;
                        windowSaveNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExistingArticle = new SaveExistingDocument();
                        windowSaveExistingArticle.Closed += ExistingSaveWindowClosed;
                        windowSaveExistingArticle.Show();
                    }
                }
                else
                {
                    MessageBox.Show("Geen aanpassingen doorgevoert", "Data opslaan", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }


        /// <summary>
        ///  checks if every field is filled in and saves a new or changed article
        /// </summary>
        /// <returns></returns>
        private bool Save()
        {
            ArrayList errors = new ArrayList();
            if (txt_title.Text == "")
            {
                errors.Add("Geen titel ingevuld.");
            }
            if (txt_tags.Text == "")
            {
                errors.Add("Geen tag(s) ingevuld.");
            }
            if (cb_cat.SelectedIndex == 0)
            {
                errors.Add("Geen catgeorie toegewezen.");
            }
            if (GetVisibility() == INFORMATION)
            {
                if (txt_artikel.Text == "")
                {
                    errors.Add("Geen informatie-tekst ingevuld.");
                }
            }
            else if (GetVisibility() == PROBLEM)
            {
                if (txt_problem.Text == "")
                {
                    errors.Add("Geen problem-tekst ingevuld.");
                }
            }
            if (errors.Count > 0)
            {
                string errorMessage = "";
                foreach (string s in errors)
                {
                    errorMessage += s + "\n\n";
                }
                MessageBox.Show("Opslaan niet mogelijk:\n\n\n" + errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            else
            {
                string[] splitted = txt_tags.Text.Split(',');
                ArrayList al = new ArrayList();
                foreach (string s in splitted)
                {
                    al.Add(s.Trim());
                }
                try
                {
                    using (var svc = new KennismanagementClient())
                    {
                        if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                        {
                            svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                        }
                        if (newData)
                        {
                            if (GetVisibility() == INFORMATION)
                            {
                                shownArticle = svc.insertInformation(txt_author.Text, txt_title.Text, cb_cat.Text, txt_artikel.Text, (string[])al.ToArray(typeof(string)));
                            }
                            else if (GetVisibility() == PROBLEM)
                            {
                                shownArticle = svc.insertProblem(txt_author.Text, txt_title.Text, cb_cat.Text, txt_problem.Text, txt_solution.Text, (string[])al.ToArray(typeof(string)));
                            }
                            newData = false;
                        }
                        else if (!newData)
                        {
                            string editor = Properties.Settings.Default.LastName + " " + Properties.Settings.Default.FirstName.Substring(0, 1) + ".";
                            if (GetVisibility() == INFORMATION)
                            {
                                shownArticle = svc.updateInformation(shownArticle, DateTime.ParseExact(txt_dateCreated.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture), txt_author.Text, editor, txt_title.Text, cb_cat.Text, txt_artikel.Text, (string[])al.ToArray(typeof(string)));
                                txt_editor.Text = editor;
                                txt_dateEdited.Text = DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year;
                            }
                            else if (GetVisibility() == PROBLEM)
                            {
                                shownArticle = svc.updateProblem(shownArticle, DateTime.ParseExact(txt_dateCreated.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture), txt_author.Text, editor, txt_title.Text, cb_cat.Text, txt_problem.Text, txt_solution.Text, (string[])al.ToArray(typeof(string)));
                                txt_editor.Text = editor;
                                txt_dateEdited.Text = DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year;
                            }
                        }
                        svc.Close();
                        SetInformationStatus(false);
                        Reset();
                        RefreshArticle();
                        SetInformationStatus(true);

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                return true;
            }
        }
        /// <summary>
        ///  saves a category on the server
        /// </summary>
        /// <returns></returns>
        private bool SaveCategory()
        {
            try
            {
                using (var svc = new KennismanagementClient())
                {
                    if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                    {
                        svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                    }
                    svc.addCategory(cat.categoryName);
                    svc.Close();
                }
                if (GetVisibility() == INFORMATION || GetVisibility() == PROBLEM)
                {
                    ShowCategories();
                    ComboBoxItem cbItem = new ComboBoxItem();
                    cbItem.Content = cat.categoryName;
                    cb_cat.SelectedIndex = cb_cat.Items.IndexOf(cat.categoryName);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + e, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            return true;
        }

        /// <summary>
        ///  opens the seach GUI and opens the save dialog if there is something to save
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartSearch(object sender, RoutedEventArgs e)
        {
            if (GetVisibility() == INFORMATION)
            {
                if (HeaderChanged() || artikelChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += NewSaveWindowOnSearchClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveWindowOnSearchClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    SetInformationStatus(false);
                    ChangeVisibility(SEARCH);
                    Search();
                }
            }
            else if (GetVisibility() == PROBLEM)
            {
                if (HeaderChanged() || problemChanged || solutionChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += NewSaveWindowOnSearchClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveWindowOnSearchClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    SetInformationStatus(false);
                    ChangeVisibility(SEARCH);
                    Search();
                }
            }
            else
            {
                Search();
            }
        }
        /// <summary>
        /// connects to the server and calls the function findArticleWithCategory() on it, then displayes the search results
        /// </summary>
        private void Search()
        {
            string searchTag = txt_search.Text;
            if (searchTag.Length > 0)
            {
                if (_ArticleCollection.Count > 0)
                {
                    _ArticleCollection.Clear();
                }
                using (var svc = new KennismanagementClient())
                {
                    if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                    {
                        svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                    }
                    stringArray[] resultCategories = svc.findArticleWithCategory(searchTag, displayOutdatedFiles);
                    stringArray[] resultTags = svc.findArticleWithHeaderData(searchTag, displayOutdatedFiles);
                    svc.Close();
                    stringArray[] results;
                    if (resultCategories != null && resultTags != null && resultCategories.Length > 0 && resultTags.Length > 0)
                    {
                        if (resultCategories.Length > 0 && resultTags.Length > 0)
                        {
                            results = new Helper().mergeListViewItemsAlphabetical(resultCategories, resultTags, displayOutdatedFiles);
                        }
                        else if (resultCategories.Length > 0 && resultTags.Length < 1)
                        {
                            results = new Helper().sortListViewItemsAlphabetical(resultCategories);
                        }
                        else
                        {
                            results = new Helper().sortListViewItemsAlphabetical(resultTags);
                        }
                    }
                    else if (resultCategories == null && resultTags != null)
                    {
                        if (resultTags.Length > 0)
                        {
                            results = new Helper().sortListViewItemsAlphabetical(resultTags);
                        }
                        else
                        {
                            results = results = new stringArray[0];
                        }
                    }
                    else if (resultCategories != null && resultTags == null)
                    {
                        if (resultCategories.Length > 0)
                        {
                            results = new Helper().sortListViewItemsAlphabetical(resultCategories);
                        }
                        else
                        {
                            results = results = new stringArray[0];
                        }
                    }
                    else
                    {
                        results = new stringArray[0];
                    }
                    int searchResults;
                    if (results.Length > 0)
                    {
                        FillList(results);
                        searchResults = results.Length;
                    }
                    else
                    {
                        searchResults = 0;
                    }
                    lb_headline.Content = searchResults + " Zoekresulten:";
                    list_categories.SelectedIndex = -1;
                }
            }
        }

        /// <summary>
        ///  closes an open GUI and opens the main GUI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Close(object sender, RoutedEventArgs e)
        {
            bool infoChanged = HeaderChanged();
            if (GetVisibility() == INFORMATION)
            {
                if (infoChanged || artikelChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += newSaveExitWindowClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveExitWindowClosed;
                        windowSaveExitExistingArticle.Show();
                    }

                }
                else
                {
                    list_results.SelectedItem = null;
                    list_results.LostFocus += ListViewLostFocus;
                    ChangeVisibility(SEARCH);
                    RefreshMain();
                }
            }
            else if (GetVisibility() == PROBLEM)
            {
                if (infoChanged || problemChanged || solutionChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += newSaveExitWindowClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveExitWindowClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    list_results.SelectedItem = null;
                    list_results.LostFocus += ListViewLostFocus;
                    ChangeVisibility(SEARCH);
                    RefreshMain();
                }
            }
        }

        /// <summary>
        ///  opens a pop up with a delete dialog if button is pushed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteClick(object sender, RoutedEventArgs e)
        {
            removeArticle = new RemoveDocument();
            removeArticle.Closed += WindowRemoveClosed;
            removeArticle.Show();
        }

        /// <summary>
        ///  closes the program
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exit(object sender, RoutedEventArgs e)
        {
            if (cat != null)
            {
                cat.Close();
            }
            Environment.Exit(0);
        }

        /// <summary>
        ///  tries to connect the server and rates the viewed article down when thump is klicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnThumpDownClick(object sender, RoutedEventArgs e)
        {
            if (!newData)
            {

                try
                {
                    using (var svc = new KennismanagementClient())
                    {
                        if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                        {
                            svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                        }
                        ArticleInformation item = null;
                        for (int i = 0; i < _ArticleCollection.Count; i++)
                        {
                            if (_ArticleCollection.ElementAt(i).Id == shownArticle)
                            {
                                item = _ArticleCollection.ElementAt(i);
                                break;
                            }
                        }
                        if (item != null)
                        {
                            svc.rateArticle(item.Id, item.Type, Properties.Settings.Default.LastName + " " + Properties.Settings.Default.FirstName.Substring(0, 1) + ".", "--");
                            if (item.Type == "Information")
                            {
                                int rating = svc.getInformationRating(item.Id);
                                txt_rating_article.Text = Convert.ToString(rating);
                                _ArticleCollection.ElementAt(_ArticleCollection.IndexOf(item)).Rating = Convert.ToString(rating);
                            }
                            else if (item.Type == "Problem")
                            {
                                int rating = svc.getProblemRating(item.Id);
                                txt_rating_article.Text = Convert.ToString(rating);
                                _ArticleCollection.ElementAt(_ArticleCollection.IndexOf(item)).Rating = Convert.ToString(rating);
                            }
                        }
                        svc.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else
            {
                MessageBox.Show("Bestand niet opgeslann rating kan niet doorgevoert worden.", "Bestand bestaat nog niet in het systeem", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        /// <summary>
        ///  tries to connect the server and rates the viewed article up when thump is klicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnThumpUpClick(object sender, RoutedEventArgs e)
        {
            if (!newData)
            {

                try
                {
                    using (var svc = new KennismanagementClient())
                    {
                        if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                        {
                            svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                        }
                        ArticleInformation item = null;
                        bool existing = false;
                        for (int i = 0; i < _ArticleCollection.Count; i++)
                        {
                            if (_ArticleCollection.ElementAt(i).Id == shownArticle)
                            {
                                item = _ArticleCollection.ElementAt(i);
                                existing = true;
                                break;
                            }
                        }
                        if (existing == false)
                        {
                            item = new ArticleInformation();
                            item.Id = shownArticle;
                            if (GetVisibility() == INFORMATION)
                            {
                                item.Type = "Information";
                                txt_rating_article.Text = Convert.ToString(svc.getInformationRating(shownArticle));
                            }
                            else if (GetVisibility() == PROBLEM)
                            {
                                item.Type = "Problem";
                                txt_rating_article.Text = Convert.ToString(svc.getProblemRating(shownArticle));
                            }
                        }
                        if (item != null)
                        {
                            svc.rateArticle(item.Id, item.Type, Properties.Settings.Default.LastName + ", " + Properties.Settings.Default.FirstName, "++");
                            if (item.Type == "Information")
                            {
                                int rating = svc.getInformationRating(item.Id);
                                txt_rating_article.Text = Convert.ToString(rating);
                                if (existing)
                                {
                                    _ArticleCollection.ElementAt(_ArticleCollection.IndexOf(item)).Rating = Convert.ToString(rating);
                                }
                            }
                            else if (item.Type == "Problem")
                            {
                                int rating = svc.getProblemRating(item.Id);
                                txt_rating_article.Text = Convert.ToString(rating);
                                if (existing)
                                {
                                    _ArticleCollection.ElementAt(_ArticleCollection.IndexOf(item)).Rating = Convert.ToString(rating);
                                }
                            }
                        }
                        svc.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            else
            {
                MessageBox.Show("Bestand niet opgeslaan rating kan niet doorgevoert worden.", "Bestand bestaat nog niet in het systeem", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }


        /// <summary>
        ///  fills the mainList depending on certain typ (category/search) and a certain qualifier
        /// </summary>
        /// <param name="data"></param>
        private void FillList(stringArray[] data)
        {
            for (int i = 0; i < data.Length; i++)
            {
                if (data[i].item != null)
                {
                    string lastEdited = data[i].item.ElementAt(2);
                    if (lastEdited == null || lastEdited == "")
                    {
                        lastEdited = data[i].item.ElementAt(1);
                    }
                    string editor = data[i].item.ElementAt(5);
                    if (editor == null || editor == "")
                    {
                        editor = "geen";
                    }
                    _ArticleCollection.Add(new ArticleInformation
                    {
                        Id = Convert.ToInt32(data[i].item.ElementAt(0)),
                        Title = data[i].item.ElementAt(6),
                        Type = data[i].item.ElementAt(7),
                        Author = data[i].item.ElementAt(4),
                        Editor = editor,
                        Rating = data[i].item.ElementAt(8),
                        Created = data[i].item.ElementAt(1),
                        LastEdited = lastEdited
                    });
                }
            }
        }


        /// <summary>
        ///  displayes categories in an alphabetical order
        /// </summary>
        private void ShowCategories()
        {
            try
            {
                using (var svc = new KennismanagementClient())
                {
                    if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                    {
                        svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                    }
                    stringArray[] categories = svc.getCategories();
                    categories = new Helper().mergeCategoriesAlphabetical(categories, categories);
                    svc.Close();
                    if (categories != null)
                    {
                        for (int i = 0; i < categories.Length; i++)
                        {
                            cb_cat.Items.Add(categories[i].item.ElementAt(1));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }


        /// <summary>
        ///  changes between the different views of the application
        /// </summary>
        /// <param name="window"></param>
        private void ChangeVisibility(int window)
        {
            switch (window)
            {
                case SEARCH:
                    if (sub_search.Visibility == Visibility.Hidden)
                    {
                        Reset();
                        if (sub_artikel.Visibility == Visibility.Visible)
                        {
                            sub_artikel.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            sub_problem.Visibility = Visibility.Hidden;
                        }
                        sub_search.Visibility = Visibility.Visible;
                    }
                    break;
                case INFORMATION:
                    if (sub_artikel.Visibility == Visibility.Hidden)
                    {
                        if (sub_search.Visibility == Visibility.Visible)
                        {
                            sub_search.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            sub_problem.Visibility = Visibility.Hidden;
                        }
                        sub_artikel.Visibility = Visibility.Visible;
                        ShowCategories();
                    }
                    break;
                case PROBLEM:
                    if (sub_problem.Visibility == Visibility.Hidden)
                    {
                        if (sub_search.Visibility == Visibility.Visible)
                        {
                            sub_search.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            sub_artikel.Visibility = Visibility.Hidden;
                        }
                        sub_problem.Visibility = Visibility.Visible;
                        ShowCategories();
                    }
                    break;
            }
        }


        /// <summary>
        ///  return the visibility of the application window
        /// </summary>
        /// <returns></returns>
        private int GetVisibility()
        {
            if (sub_search.Visibility == Visibility.Visible)
            {
                return SEARCH;
            }
            else if (sub_artikel.Visibility == Visibility.Visible)
            {
                return INFORMATION;
            }
            else if (sub_problem.Visibility == Visibility.Visible)
            {
                return PROBLEM;
            }
            else
            {
                return -1;
            }
        }


        /// <summary>
        ///  defines category type depending on the radio buttons
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RadioButtonChecked(object sender, RoutedEventArgs e)
        {
            if (list_categories != null)
            {
                if (list_categories.Items.Count > 0)
                {
                    list_categories.Items.Clear();
                }
            }
            if (rad_all.IsChecked == true)
            {
                type = "all";
            }
            else if (rad_artikel.IsChecked == true)
            {
                type = "information";
            }
            else if (rad_problem.IsChecked == true)
            {
                type = "problem";
            }
            if (list_categories != null && list_categories.IsInitialized)
            {
                SetListCategories(sender, e);
            }

        }



        /// <summary>
        ///  recevies the categories form the server and fills the category list depending on the category type
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SetListCategories(object sender, EventArgs e)
        {
            try
            {
                using (var svc = new KennismanagementClient())
                {
                    if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                    {
                        svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                    }
                    ListViewItem listItemAll = new ListViewItem();
                    listItemAll.Name = "list_item_all";
                    listItemAll.Content = "Alle";
                    listItemAll.Cursor = Cursors.Hand;
                    listItemAll.IsSelected = true;
                    Separator seperator = new Separator();
                    seperator.Margin = new Thickness(-5, 0, 5, 0);
                    list_categories.Items.Add(listItemAll);
                    list_categories.Items.Add(seperator);

                    if (type == "all")
                    {
                        stringArray[] catInfromation = svc.getInformationCategories(displayOutdatedFiles);
                        stringArray[] catProblems = svc.getProblemCategories(displayOutdatedFiles);
                        stringArray[] merged = new Helper().mergeCategoriesAlphabetical(catInfromation, catProblems);

                        for (int i = 0; i < merged.Length; i++)
                        {
                            ListViewItem catCurrent = new ListViewItem();
                            catCurrent.Content = merged[i].item.ElementAt(1);
                            catCurrent.Name = "list_categories_" + merged[i].item.ElementAt(0);
                            catCurrent.Cursor = Cursors.Hand;
                            list_categories.Items.Add(catCurrent);
                        }

                    }
                    else if (type == "information")
                    {
                        stringArray[] catInfromation = svc.getInformationCategories(displayOutdatedFiles);
                        catInfromation = new Helper().sortCategoriesAlphabetical(catInfromation);
                        for (int i = 0; i < catInfromation.Length; i++)
                        {
                            ListViewItem catCurrent = new ListViewItem();
                            catCurrent.Content = catInfromation[i].item.ElementAt(1);
                            catCurrent.Name = "list_categories_" + catInfromation[i].item.ElementAt(0);
                            catCurrent.Cursor = Cursors.Hand;
                            list_categories.Items.Add(catCurrent);
                        }
                    }
                    else if (type == "problem")
                    {
                        stringArray[] catProblems = svc.getProblemCategories(displayOutdatedFiles);
                        catProblems = new Helper().sortCategoriesAlphabetical(catProblems);
                        for (int i = 0; i < catProblems.Length; i++)
                        {
                            ListViewItem catCurrent = new ListViewItem();
                            catCurrent.Content = catProblems[i].item.ElementAt(1);
                            catCurrent.Name = "list_categories_" + catProblems[i].item.ElementAt(1);
                            // catCurrent.GotMouseCapture
                            catCurrent.Cursor = Cursors.Hand;
                            list_categories.Items.Add(catCurrent);
                        }
                    }
                    svc.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        /// <summary>
        ///  shows either all categories or only information categories or problem categories  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ListCategoriesSelectionChanged(object sender, SelectionChangedEventArgs args)
        {
            ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
            try
            {
                if (type == "all")
                {
                    lb_headline.Content = "Overzicht informatie- & oplossing voor een probleem artikelen,";
                }
                else if (type == "information")
                {
                    lb_headline.Content = "Overzicht informatie artikelen,";
                }
                else if (type == "problem")
                {
                    lb_headline.Content = "Overzicht oplossing voor en probleem artikelen,";
                }
                lb_headline.Content += " categorie: " + lbi.Content;
            }
            catch { }
            try
            {
                if (lbi != null)
                {
                    if (_ArticleCollection.Count > 0)
                    {
                        _ArticleCollection.Clear();
                    }
                    using (var svc = new KennismanagementClient())
                    {
                        if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                        {
                            svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                        }
                        stringArray[] categoryItems = null;
                        if (lbi.Content.ToString() == "Alle")
                        {
                            stringArray[] merged = new stringArray[0];
                            if (type == "all")
                            {
                                stringArray[] catInfromation = svc.getInformationCategories(displayOutdatedFiles);
                                stringArray[] catProblems = svc.getProblemCategories(displayOutdatedFiles);
                                merged = new Helper().mergeCategoriesAlphabetical(catInfromation, catProblems);
                            }
                            else if (type == "information")
                            {
                                stringArray[] catInfromation = svc.getInformationCategories(displayOutdatedFiles);
                                merged = new Helper().sortCategoriesAlphabetical(catInfromation);
                            }
                            else if (type == "problem")
                            {
                                stringArray[] catProblems = svc.getProblemCategories(displayOutdatedFiles);
                                merged = new Helper().sortCategoriesAlphabetical(catProblems);
                            }
                            if (merged != null)
                            {
                                int size = 0;
                                for (int i = 0; i < merged.Length; i++)
                                {
                                    size += merged[i].item.Count();
                                }
                                for (int i = 0; i < merged.Length; i++)
                                {
                                    categoryItems = new Helper().mergeListViewItemsAlphabetical(categoryItems, svc.findArticleWithCategory(merged[i].item.ElementAt(1), displayOutdatedFiles), displayOutdatedFiles);
                                }
                            }
                        }
                        else
                        {
                            categoryItems = svc.findArticleWithCategory(lbi.Content.ToString(), displayOutdatedFiles);
                        }
                        svc.Close();
                        if (categoryItems != null)
                        {
                            Helper helper = new Helper();
                            categoryItems = helper.removeItemsByType(categoryItems, type);
                            if (categoryItems.Count() > 1)
                            {
                                categoryItems = helper.mergeListViewItemsAlphabetical(categoryItems, categoryItems, displayOutdatedFiles);
                            }
                            FillList(categoryItems);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

        }


        /// <summary>
        ///  loads the header data for articles from sthe server and fills the header fields with it
        /// </summary>
        /// <param name="item"></param>
        private void SetHeaderData(ArticleInformation item)
        {
            string[] tags = new string[0];
            txt_author.Text = item.Author;
            txt_editor.Text = item.Editor;
            txt_title.Text = item.Title;
            txt_dateCreated.Text = item.Created;
            txt_dateEdited.Text = item.LastEdited;
            try
            {
                using (var svc = new KennismanagementClient())
                {
                    if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                    {
                        svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                    }
                    if (item.Type == "Information")
                    {
                        tags = svc.getInfromationTags(item.Id);
                    }
                    else if (item.Type == "Problem")
                    {
                        tags = svc.getProblemTags(item.Id);
                    }
                    svc.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            int tagsLength = tags.Length;
            if (tagsLength > 0)
            {
                txt_tags.Text = tags[0];
                if (tagsLength > 1)
                {
                    for (int i = 1; i < tagsLength; i++)
                    {
                        txt_tags.Text += ", " + tags[i];
                    }
                }
            }
        }


        /// <summary>
        /// gets called whenever the listView ist clicked and a document is opened and opens a popup in case of changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListCategoriesGotMouseCapture(object sender, MouseEventArgs e)
        {
            if (GetVisibility() == INFORMATION || GetVisibility() == PROBLEM)
            {
                if (HeaderChanged() || artikelChanged || problemChanged || solutionChanged)
                {
                    if (newData)
                    {
                        windowSaveExitNewArticle = new SaveExitNewDocument();
                        windowSaveExitNewArticle.Closed += newSaveExitWindowClosed;
                        windowSaveExitNewArticle.Show();
                    }
                    else
                    {
                        windowSaveExitExistingArticle = new SaveExitExistingDocument();
                        windowSaveExitExistingArticle.Closed += ExistingSaveExitWindowClosed;
                        windowSaveExitExistingArticle.Show();
                    }
                }
                else
                {
                    ChangeVisibility(SEARCH);
                    ListBoxItem lbi = ((sender as ListBox).SelectedItem as ListBoxItem);
                    if (type == "all")
                    {
                        lb_headline.Content = "Overzicht informatie- & oplossing voor een probleem artikelen,";
                    }
                    else if (type == "information")
                    {
                        lb_headline.Content = "Overzicht informatie artikelen,";
                    }
                    else if (type == "problem")
                    {
                        lb_headline.Content = "Overzicht oplossing voor en probleem artikelen,";
                    }
                    lb_headline.Content += " categorie: " + lbi.Content;
                }
            }
        }


        /// <summary>
        /// when the user clicks on a category, this function displayes the articles in it
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewSelectionChanged(object sender, RoutedEventArgs e)
        {
            if (sub_search.Visibility == Visibility.Visible)
            {
                ArticleInformation item = ((ListView)e.OriginalSource).SelectedItem as ArticleInformation;
                if (item != null)
                {
                    string category = "";
                    try
                    {
                        using (var svc = new KennismanagementClient())
                        {
                            if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                            {
                                svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                            }
                            if (item.Type == "Information")
                            {
                                category = svc.getInformationCategory(item.Id);
                            }
                            else if (item.Type == "Problem")
                            {
                                category = svc.getProblemCategory(item.Id);
                            }
                            svc.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    if (category != "")
                    {
                        while (cb_cat.Items.Count > 1)
                        {
                            cb_cat.Items.RemoveAt(1);
                        }
                        int id = cb_cat.Items.Add(category);
                        cb_cat.SelectedIndex = id;
                    }
                    cb_cat.IsEnabled = false;
                    SetHeaderData(item);
                }
            }
        }

        /// <summary>
        /// when the focus in the article overview is lost it resets the header
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewLostFocus(object sender, RoutedEventArgs e)
        {
            ResetTextfields();
            while (cb_cat.Items.Count > 1)
            {
                cb_cat.Items.RemoveAt(1);
            }
            cb_cat.SelectedIndex = 0;
            cb_cat.IsEnabled = true;
        }


        /// <summary>
        ///  when double clicked on an article in the overview, it gets the article-data from the server aand displays it
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListViewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            list_results.LostFocus -= ListViewLostFocus;
            ArticleInformation item = ((FrameworkElement)e.OriginalSource).DataContext as ArticleInformation;
            if (item != null)
            {
                ResetTextfields();
                while (cb_cat.Items.Count > 1)
                {
                    cb_cat.Items.RemoveAt(1);
                }
                cb_cat.IsEnabled = true;
                shownArticle = item.Id;
                try
                {
                    using (var svc = new KennismanagementClient())
                    {
                        if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                        {
                            svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                        }
                        string category = "";
                        SetHeaderData(item);
                        if (item.Type == "Information")
                        {
                            txt_artikel.Text = svc.getInfromationById(item.Id)[0];
                            category = svc.getInformationCategory(item.Id);
                            txt_rating_article.Text = Convert.ToString(svc.getInformationRating(item.Id));
                            ChangeVisibility(INFORMATION);
                        }
                        else if (item.Type == "Problem")
                        {
                            string[] problem = svc.getProblemById(item.Id);
                            txt_problem.Text = problem[0];
                            txt_solution.Text = problem[1];
                            category = svc.getProblemCategory(item.Id);
                            txt_rating_problem.Text = Convert.ToString(svc.getProblemRating(item.Id));
                            ChangeVisibility(PROBLEM);
                        }
                        svc.Close();
                        if (category != "")
                        {
                            cb_cat.SelectedIndex = cb_cat.Items.IndexOf(category);
                        }
                        SetInformationStatus(true);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }


        /// <summary>
        /// closes the save dialog
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void catWindowClosed(object sender, EventArgs e)
        {
            if (cat.saveAction)
            {
                SaveCategory();
            }
            cat = null;
        }


        /// <summary>
        /// gets called when the window for changing the referenceAdress is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void registerReferenceAddressClosed(object sender, EventArgs e)
        {
            RefreshMain();
            windowRegisterReferenceAddress.Closed -= registerReferenceAddressClosed;
            windowRegisterReferenceAddress = null;
        }


        /// <summary>
        ///  executes when delete dialog is closed and deletes the article on the server if the user clicked yes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowRemoveClosed(object sender, EventArgs e)
        {
            if (removeArticle.removeAction)
            {
                if (GetVisibility() == SEARCH)
                {
                    ListBoxItem lbi = (list_results.SelectedItem as ListBoxItem);
                    var item = lbi.DataContext as ArticleInformation;
                    String articleType = _ArticleCollection[ArticleCollection.IndexOf(item)].Type;
                    if (articleType == "Information")
                    {
                        try
                        {
                            using (var svc = new KennismanagementClient())
                            {
                                if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                                {
                                    svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                                }
                                svc.removeInformation(_ArticleCollection[_ArticleCollection.IndexOf(item)].Id);
                                svc.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                    else if (articleType == "Problem")
                    {
                        try
                        {
                            using (var svc = new KennismanagementClient())
                            {
                                if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                                {
                                    svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                                }
                                svc.removeProblem(_ArticleCollection[_ArticleCollection.IndexOf(item)].Id);
                                svc.Close();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                }
                else if (GetVisibility() == INFORMATION)
                {
                    try
                    {
                        using (var svc = new KennismanagementClient())
                        {
                            if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                            {
                                svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                            }
                            svc.removeInformation(shownArticle);
                            svc.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
                else if (GetVisibility() == PROBLEM)
                {
                    try
                    {
                        using (var svc = new KennismanagementClient())
                        {
                            if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                            {
                                svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                            }
                            svc.removeProblem(shownArticle);
                            svc.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
                if (GetVisibility() != SEARCH)
                {
                    ChangeVisibility(SEARCH);
                }
                RefreshMain();
            }
            removeArticle = null;
        }


        /// <summary>
        ///  executed when save dialog is closed and saves the new article if the user clicked yes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewSaveWindowClosed(object sender, EventArgs e)
        {
            if (windowSaveNewArticle.saveAction)
            {
                Save();
            }
            windowSaveNewArticle = null;
        }

        /// <summary>
        /// gets called, when the popup for saving a new article is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newSaveExitWindowClosed(object sender, EventArgs e)
        {
            if (!windowSaveExitNewArticle.cancelAction)
            {
                if (windowSaveExitNewArticle.saveAction)
                {
                    Save();
                }
                ChangeVisibility(SEARCH);
                ListBoxItem lbi = (list_categories.SelectedItem as ListBoxItem);
                if (type == "all")
                {
                    lb_headline.Content = "Overzicht informatie- & oplossing voor een probleem artikelen,";
                }
                else if (type == "information")
                {
                    lb_headline.Content = "Overzicht informatie artikelen,";
                }
                else if (type == "problem")
                {
                    lb_headline.Content = "Overzicht oplossing voor en probleem artikelen,";
                }
                lb_headline.Content += " categorie: " + lbi.Content;
            }
            windowSaveExitNewArticle = null;
            RefreshMain();
        }

        /// <summary>
        /// gets called and saves an existing article, if the user pushed the save button before
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExistingSaveWindowClosed(object sender, EventArgs e)
        {
            if (windowSaveExistingArticle.saveAction)
            {
                Save();
            }
            windowSaveExistingArticle = null;
        }

        /// <summary>
        /// gets called, when the popup for saving an existing article is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExistingSaveExitWindowClosed(object sender, EventArgs e)
        {
            if (!windowSaveExitExistingArticle.cancelAction)
            {
                if (windowSaveExitExistingArticle.saveAction)
                {
                    Save();
                }
                ChangeVisibility(SEARCH);
                ListBoxItem lbi = (list_categories.SelectedItem as ListBoxItem);
                if (type == "all")
                {
                    lb_headline.Content = "Overzicht informatie- & oplossing voor een probleem artikelen,";
                }
                else
                {
                    if (type == "information")
                    {
                        lb_headline.Content = "Overzicht informatie artikelen,";
                    }
                    else if (type == "problem")
                    {
                        lb_headline.Content = "Overzicht oplossing voor en probleem artikelen,";
                    }
                    lb_headline.Content += " categorie: " + lbi.Content;
                }
            }
            windowSaveExitExistingArticle = null;
            RefreshMain();
        }

        /// <summary>
        /// opens a popup whith a save dialog, when a new information is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewSaveWindowOnInformationClosed(object sender, EventArgs e)
        {
            if (windowSaveExitNewArticle.saveAction)
            {
                Save();
            }
            else if (!windowSaveExitNewArticle.cancelAction)
            {
                SetInformationStatus(false);
                NewArticleFromArticleView();
                ResetTextfields();
                if (newData)
                {
                    newData = false;
                }
                SetInformationStatus(true);
            }
            windowSaveExitNewArticle = null;
        }

        /// <summary>
        /// opens a popup whith a save dialog, when an existing information is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExistingSaveWindowOnInformationClosed(object sender, EventArgs e)
        {
            if (windowSaveExitExistingArticle.saveAction)
            {
                Save();
            }
            else if (!windowSaveExitExistingArticle.cancelAction)
            {
                SetInformationStatus(false);
                NewArticleFromArticleView();
                ResetTextfields();
                if (newData)
                {
                    newData = false;
                }
                SetInformationStatus(true);
            }
            windowSaveExitExistingArticle = null;
        }

        /// <summary>
        /// opens a popup whith a save dialog, when a new problem is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewSaveWindowOnProblemClosed(object sender, EventArgs e)
        {
            if (windowSaveExitNewArticle.saveAction)
            {
                Save();
            }
            else if (!windowSaveExitNewArticle.cancelAction)
            {
                SetInformationStatus(false);
                NewArticleFromArticleView();
                ResetTextfields();
                if (newData)
                {
                    newData = false;
                }
                SetInformationStatus(true);
            }
            windowSaveExitNewArticle = null;
        }

        /// <summary>
        /// opens a popup whith a save dialog, when an existing problem is closed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExistingSaveWindowOnProblemClosed(object sender, EventArgs e)
        {
            if (windowSaveExitExistingArticle.saveAction)
            {
                Save();
            }
            else if (!windowSaveExitExistingArticle.cancelAction)
            {
                SetInformationStatus(false);
                NewArticleFromArticleView();
                ResetTextfields();
                if (newData)
                {
                    newData = false;
                }
                SetInformationStatus(true);
            }
            windowSaveExitExistingArticle = null;
        }


        /// <summary>
        /// gets called when the search is closed and saves an article, if the user wanted to
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewSaveWindowOnSearchClosed(object sender, EventArgs e)
        {
            if (windowSaveExitNewArticle.saveAction)
            {
                Save();
            }
            else if (!windowSaveExitNewArticle.cancelAction)
            {
                ChangeVisibility(SEARCH);
                if (newData)
                {
                    newData = false;
                }
                Search();
            }
            windowSaveExitNewArticle = null;
        }


        /// <summary>
        /// catches close event of the save window, that comes up if an article which is new, or altered and consists unsaved data is opened and the user tries a search action
        /// </summary>
        /// <param name="sender">saveExitWindow</param>
        /// <param name="e">closeEvent</param>
        private void ExistingSaveWindowOnSearchClosed(object sender, EventArgs e)
        {
            if (windowSaveExitExistingArticle.saveAction)
            {
                Save();
            }
            else if (!windowSaveExitExistingArticle.cancelAction)
            {
                ChangeVisibility(SEARCH);
                if (newData)
                {
                    newData = false;
                }
                Search();
            }
            windowSaveExitExistingArticle = null;
        }

        /// <summary>
        /// switches to the new article GUI
        /// </summary>
        private void NewArticleFromArticleView()
        {
            if (menuItemClicked == INFORMATION)
            {
                ChangeVisibility(INFORMATION);
                NewInformationArticle();
            }
            else if (menuItemClicked == PROBLEM)
            {
                ChangeVisibility(PROBLEM);
                NewProblemArticle();
            }
        }

        /// <summary>
        ///  sorts the overview by the column that was clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortByColumn(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader headerClicked =
              e.OriginalSource as GridViewColumnHeader;
            ListSortDirection direction;

            if (headerClicked != null)
            {
                if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
                {
                    if (headerClicked != _lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (_lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }
                    string header = headerClicked.Column.Header as string;
                    Sort(header, direction);

                    if (direction == ListSortDirection.Ascending)
                    {
                        headerClicked.Column.HeaderTemplate =
                          Resources["HeaderTemplateArrowUp"] as DataTemplate;
                    }
                    else
                    {
                        headerClicked.Column.HeaderTemplate =
                          Resources["HeaderTemplateArrowDown"] as DataTemplate;
                    }
                    // Remove arrow from previously sorted header
                    if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
                    {
                        _lastHeaderClicked.Column.HeaderTemplate = null;
                    }
                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
        }


        /// <summary>
        ///  determines how the overview list is sorted
        /// </summary>
        /// <param name="sortBy"></param>
        /// <param name="direction"></param>
        private void Sort(string sortBy, ListSortDirection direction)
        {
            ICollectionView dataView =
              CollectionViewSource.GetDefaultView(list_results.ItemsSource);

            dataView.SortDescriptions.Clear();
            if (sortBy == "Auteur")
            {
                sortBy = "Author";
            }
            if (sortBy == "Titel")
            {
                sortBy = "Title";
            }
            if (sortBy == "Laatst aangepast")
            {
                sortBy = "LastEdited";
            }
            SortDescription sd = new SortDescription(sortBy, direction);
            dataView.SortDescriptions.Add(sd);
            dataView.Refresh();
        }



        /// <summary>
        ///  sets global val tagsChanged on true if a tag has been changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextChanged(object sender, EventArgs e)
        {
            if (sender.Equals(txt_tags))
            {
                tagsChanged = true;
            }
            else if (sender.Equals(txt_title))
            {
                titleChanged = true;
            }
            else if (sender.Equals(txt_artikel))
            {
                artikelChanged = true;
            }
            else if (sender.Equals(txt_problem))
            {
                problemChanged = true;
            }
            else if (sender.Equals(txt_solution))
            {
                solutionChanged = true;
            }
            else if (sender.Equals(cb_cat))
            {
                catChanged = true;
            }
        }


        /// <summary>
        ///  sets tags to read only or editable
        /// </summary>
        /// <param name="active"></param>
        private void SetInformationStatus(bool active)
        {
            if (active)
            {
                txt_tags.IsReadOnly = false;
                txt_title.IsReadOnly = false;
                txt_tags.IsEnabled = true;
                txt_title.IsEnabled = true;
                if (GetVisibility() == INFORMATION)
                {
                    txt_artikel.IsReadOnly = false;
                    txt_artikel.TextChanged += TextChanged;
                }
                if (GetVisibility() == PROBLEM)
                {
                    txt_problem.IsReadOnly = false;
                    txt_solution.IsReadOnly = false;
                    txt_problem.TextChanged += TextChanged;
                    txt_solution.TextChanged += TextChanged;
                }
                txt_tags.TextChanged += TextChanged;
                txt_title.TextChanged += TextChanged;
                cb_cat.SelectionChanged += TextChanged;
            }
            else
            {
                txt_tags.IsReadOnly = true;
                txt_title.IsReadOnly = true;
                txt_author.IsReadOnly = true;
                txt_author.IsEnabled = false;
                txt_tags.IsEnabled = false;
                txt_title.IsEnabled = false;
                txt_dateCreated.IsEnabled = false;
                txt_dateEdited.IsEnabled = false;
                txt_editor.IsEnabled = false;
                txt_author.Foreground = Brushes.Black;
                txt_tags.Foreground = Brushes.Black;
                txt_title.Foreground = Brushes.Black;
                txt_dateCreated.Foreground = Brushes.Black;
                txt_dateEdited.Foreground = Brushes.Black;
                txt_editor.Foreground = Brushes.Black;
                if (GetVisibility() == INFORMATION)
                {
                    txt_artikel.IsReadOnly = true;
                    txt_artikel.TextChanged -= TextChanged;
                }
                if (GetVisibility() == PROBLEM)
                {
                    txt_problem.IsReadOnly = true;
                    txt_solution.IsReadOnly = true;
                    txt_problem.TextChanged -= TextChanged;
                    txt_solution.TextChanged -= TextChanged;

                    catChanged = false;
                    tagsChanged = false;
                    titleChanged = false;
                    artikelChanged = false;
                    problemChanged = false;
                    solutionChanged = false;
                }
                txt_tags.TextChanged -= TextChanged;
                txt_title.TextChanged -= TextChanged;
                cb_cat.SelectionChanged -= TextChanged;
            }
        }



        /// <summary>
        /// checks if data in the header has been changed
        /// </summary>
        /// <returns>true if tags or title fild has been changed, otherwise false</returns>  
        private bool HeaderChanged()
        {
            if (tagsChanged || titleChanged || catChanged)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// refreshes the article informations after an update has been made
        /// </summary>
        private void RefreshArticle()
        {
            try
            {
                using (var svc = new KennismanagementClient())
                {
                    if (svc.Endpoint.Address.ToString() != ConfigSettings.GetEndpointAddress())
                    {
                        svc.Endpoint.Address = new System.ServiceModel.EndpointAddress(ConfigSettings.GetEndpointAddress());
                    }
                    string[] data = new string[0];
                    if (GetVisibility() == INFORMATION)
                    {
                        data = svc.getInfromationHeaderById(shownArticle);
                    }
                    else if (GetVisibility() == PROBLEM)
                    {
                        data = svc.getProblemHeaderById(shownArticle);
                    }
                    string[] tags = new string[0];
                    string category = "";
                    txt_author.Text = data[2];
                    txt_editor.Text = data[3];
                    txt_title.Text = data[4];
                    txt_dateCreated.Text = data[0];
                    txt_dateEdited.Text = data[1];
                    if (GetVisibility() == INFORMATION)
                    {
                        tags = svc.getInfromationTags(shownArticle);
                        txt_artikel.Text = svc.getInfromationById(shownArticle)[0];
                        category = svc.getInformationCategory(shownArticle);
                        txt_rating_article.Text = Convert.ToString(svc.getInformationRating(shownArticle));
                    }
                    else if (GetVisibility() == PROBLEM)
                    {
                        tags = svc.getProblemTags(shownArticle);
                        string[] problem = svc.getProblemById(shownArticle);
                        txt_problem.Text = problem[0];
                        txt_solution.Text = problem[1];
                        category = svc.getInformationCategory(shownArticle);
                        txt_rating_problem.Text = Convert.ToString(svc.getProblemRating(shownArticle));
                    }
                    svc.Close();
                    ShowCategories();
                    if (category != "")
                    {
                        cb_cat.SelectedIndex = cb_cat.Items.IndexOf(category);
                    }
                    int tagsLength = tags.Length;
                    if (tagsLength > 0)
                    {
                        txt_tags.Text = tags[0];
                        if (tagsLength > 1)
                        {
                            for (int i = 1; i < tagsLength; i++)
                            {
                                txt_tags.Text += ", " + tags[i];
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kennismanagment API of database niet bereikbaar\n\n" + ex, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }



        /// <summary>
        /// refreshes the main ListView
        /// </summary>
        private void RefreshMain()
        {
            if (list_categories.Items.Count > 1)
            {
                string nameSelectedItem;
                if (list_categories.SelectedItem == null)
                {
                    nameSelectedItem = "Alle";
                }
                else
                {
                    nameSelectedItem = list_categories.SelectedItem.ToString();
                }
                list_categories.Items.Clear();
                SetListCategories(this, new EventArgs());
                for (int i = 0; i < list_categories.Items.Count; i++)
                {
                    if (list_categories.Items.GetItemAt(i).ToString() == nameSelectedItem)
                    {
                        list_categories.SelectedIndex = i;
                    }
                }
            }
        }


        /// <summary>
        /// clears all textfields, the combobox, etc
        /// removes bindings
        /// </summary>
        private void Reset()
        {
            while (cb_cat.Items.Count > 1)
            {
                cb_cat.Items.RemoveAt(1);
            }
            cb_cat.SelectedIndex = 0;
            ResetTextfields();
            catChanged = false;
            tagsChanged = false;
            titleChanged = false;
            artikelChanged = false;
            problemChanged = false;
            solutionChanged = false;
            newData = false;
            if (windowSaveNewArticle != null)
            {
                windowSaveNewArticle.Closed -= NewSaveWindowClosed;
                windowSaveNewArticle = null;
            }
            if (windowSaveExistingArticle != null)
            {
                windowSaveExistingArticle.Closed -= ExistingSaveWindowClosed;
                windowSaveExistingArticle = null;
            }
            if (windowSaveExitNewArticle != null)
            {
                windowSaveExitNewArticle.Closed -= newSaveExitWindowClosed;
                windowSaveExitNewArticle.Closed -= NewSaveWindowOnInformationClosed;
                windowSaveExitNewArticle.Closed -= NewSaveWindowOnProblemClosed;
                windowSaveExitNewArticle.Closed -= newSaveExitWindowClosed;
                windowSaveExitNewArticle = null;
            }
            if (windowSaveExitExistingArticle != null)
            {
                windowSaveExitExistingArticle.Closed -= ExistingSaveExitWindowClosed;
                windowSaveExitExistingArticle.Closed -= ExistingSaveWindowOnInformationClosed;
                windowSaveExitExistingArticle.Closed -= ExistingSaveWindowOnProblemClosed;
                windowSaveExitExistingArticle.Closed -= ExistingSaveWindowClosed;
                windowSaveExitExistingArticle = null;
            }
            if (searched)
            {
                list_results.Items.Clear();
                searched = false;
            }
            SetInformationStatus(false);
        }

        /// <summary>
        /// resets all textfields to empty
        /// </summary>
        private void ResetTextfields()
        {
            txt_author.Text = txt_editor.Text = "";
            txt_tags.Text = "";
            txt_title.Text = "";
            txt_artikel.Text = "";
            txt_problem.Text = "";
            txt_solution.Text = "";
            txt_dateCreated.Text = "";
            txt_dateEdited.Text = "";
        }




        private void TxtSearchGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            if (txt_search.Text.Length > 0)
            {
                txt_search.SelectAll();
            }
        }

        private void TxtSearchGotMouseCapture(object sender, MouseEventArgs e)
        {
            if (txt_search.Text.Length > 0)
            {
                txt_search.SelectAll();
            }
        }


        /// <summary>
        /// collection to store the document values for the main view
        /// </summary>
        public ObservableCollection<ArticleInformation> ArticleCollection
        { get { return _ArticleCollection; } }

        /// <summary>
        /// sets the parameters for informations and problems
        /// </summary>
        public class ArticleInformation
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Type { get; set; }
            public string Author { get; set; }
            public string Editor { get; set; }
            public string Rating { get; set; }
            public string Created { get; set; }
            public string LastEdited { get; set; }
        }

        /// <summary>
        /// handels the refresh
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshMainHandler(object sender, RoutedEventArgs e)
        {
            RefreshMain();
        }
    }
}
